package org.ithink.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class HisUtil {

	/**
	 * 把List result<HASHMAP>里面数据封装成GRID++报表数据 针对resultMap = hashMap
	 * 
	 * @param result:
	 *          行
	 * @param map:
	 *          参数
	 */
	public static String getGridXmlMap(List result, Map map) {

		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"gb2312\"?>\n");
		sb.append("<report>\n");
		sb.append("<xml>\n");
		for (int i = 0; i < result.size(); i++) {
			sb.append("<row>\n");
			Map hashMap = (HashMap) result.get(i);
			sb.append(getGridStrByMap(hashMap));
			sb.append("</row>\n");
		}

		sb.append("</xml>\n");
		sb.append("<_grparam>\n");
		sb.append(getGridStrByMap(map));
		sb.append("</_grparam>\n");
		sb.append("</report>");

		return sb.toString();
	}

	/**
	 * 把List result<Entity>里面数据封装成GRID++报表数据 针对resultMap = class
	 * 
	 * @param result:
	 *          行
	 * @param map:
	 *          参数
	 */
	public static String getGridXmlEntity(List result, Map map) {

		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"gb2312\"?>");
		sb.append("<report>\n");
		sb.append("<xml>\n");
		for (int i = 0; i < result.size(); i++) {
			sb.append("<row>\n");
			sb.append(getGridStrByEntity(result.get(i)));
			sb.append("</row>\n");
		}

		sb.append("</xml>\n");
		sb.append("<_grparam>\n");
		sb.append(getGridStrByMap(map));
		sb.append("</_grparam>\n");
		sb.append("</report>");

		return sb.toString();
	}

	/**
	 * 把HASHMAP里面数据封装成XML
	 */
	public static String getGridStrByMap(Map hashMap) {

		if (hashMap.isEmpty()) {
			return "";
		}

		StringBuffer strBuffer = new StringBuffer();
		Iterator it = hashMap.keySet().iterator();

		while (it.hasNext()) {
			String key = (String) it.next();
			Object value = hashMap.get(key);
			strBuffer.append("<" + key + "><![CDATA[" + (value == null || value == "null" ? "" : value) + "]]></" + key + ">\n");
		}

		return strBuffer.toString();
	}

	/**
	 * 把Entity里面的数据封装成XML
	 */
	public static String getGridStrByEntity(Object obj) {

		if (null == obj) {
			return "";
		}

		StringBuffer strBuffer = new StringBuffer();

		// 利用反射，动态的设置属性参数

		// 1
		Class dataClass = obj.getClass();
		Class superClass = dataClass.getSuperclass();

		Method[] methods = dataClass.getDeclaredMethods();
		Field[] fields = dataClass.getDeclaredFields();
		Method[] supmethods = superClass.getDeclaredMethods();
		Field[] supfields = superClass.getDeclaredFields();

		Method[] allMethods = new Method[methods.length + supmethods.length];
		Field[] allFields = new Field[fields.length + supfields.length];

		for (int i = 0; i < fields.length; i++) {
			allFields[i] = fields[i];
		}
		for (int i = 0; i < supfields.length; i++) {
			allFields[fields.length + i] = supfields[i];
		}
		for (int i = 0; i < methods.length; i++) {
			allMethods[i] = methods[i];
		}
		for (int i = 0; i < supmethods.length; i++) {
			allMethods[methods.length + i] = supmethods[i];
		}

		for (int i = 0; i < allFields.length; i++) {
			Field temp_fields = allFields[i];
			String temp_str = temp_fields.getName();
			String needMethodsName = "get" + temp_str.substring(0, 1).toUpperCase() + temp_str.substring(1);

			for (int k = 0; k < allMethods.length; k++) {
				Method temp_method = allMethods[k];

				if (temp_method.getName().equals(needMethodsName)) {
					try {
						Object temp_val = temp_method.invoke(obj, new Object[] {});
						String returnTypeStr = temp_method.getReturnType().getName();
						if ("java.util.Date".equals(returnTypeStr)) {
							temp_val = Convert.dataFormat((Date) temp_val, "yyyy-MM-dd HH:mm:ss");
							strBuffer.append("<" + temp_str + "><![CDATA[" + (temp_val == null ? "" : temp_val) + "]]></" + temp_str + ">\n");
						} else {
							strBuffer.append("<" + temp_str + "><![CDATA[" + (temp_val == null ? "" : temp_val.toString()) + "]]></" + temp_str + ">\n");
						}
						break;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return strBuffer.toString();
	}

	public static String formatStr(String str) {
		if (NullsUtil.isEmpty(str) ||str.trim().equalsIgnoreCase("null")){
			return str;
		}
		String indexStr = str.substring(0, 1);
		String endStr = str.substring(str.length() - 1, str.length());

		if (indexStr.equals("‘")) {
			str = str.substring(1, str.length());
		}
		if (endStr.equals("’")) {
			str = str.substring(0, str.length() - 1);
		}
		return str;
	}

	/**
	 * 根据页面所获取的处方号封装成完整的处方号
	 */
	public static String getCfCode(String cfCode, Date dbdate) {
		/*
		 * if(null != cfCode && !"".equals(cfCode)){ if(cfCode.length()<12){ String beforeCode = Convert.dataFormat(new Date(), "yyyyMMdd");
		 * if(cfCode.length()<=4){ String lastCode = cfCode; for(int i=0;i<4-cfCode.length();i++){ lastCode = "0".concat(lastCode); } cfCode =
		 * beforeCode.concat(lastCode); } if(cfCode.length()>4){ String lastCode = cfCode.substring(cfCode.length()-4, cfCode.length()); cfCode =
		 * beforeCode.concat(lastCode); } } } if("".equals(cfCode)){ cfCode = null; } return cfCode;
		 */
		if (!NullsUtil.isEmpty(cfCode)) {
			if (cfCode.length() <= 6) {
				return Convert.dataFormat(dbdate, "yyyyMMdd") + String.valueOf(1000000 + Integer.parseInt(cfCode)).substring(1);
			}
		}
		return cfCode;
	}

	public static String getRemortIP(HttpServletRequest request) {
		try {
			if (request.getHeader("x-forwarded-for") == null) {
				return request.getRemoteAddr();
			}
			return request.getHeader("x-forwarded-for");
		} catch (RuntimeException e) {
			return "";
		}
	}

	public static int current_sequence = 0;
	public static java.text.SimpleDateFormat datefm = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
	public static java.text.DecimalFormat decfm = new java.text.DecimalFormat("00000");

	public synchronized static String GetFileName() throws Exception {
		String currentRegid = "";
		String currenttime = datefm.format(new java.util.Date());
		currentRegid += currenttime;
		if (current_sequence >= 0 && current_sequence < 99999)
			current_sequence = current_sequence + 1;
		else if (current_sequence == 99999)
			current_sequence = 0;
		else
			current_sequence = 0;
		String curentid = decfm.format(current_sequence);
		currentRegid += curentid;

		return currentRegid;
	}

	public static String wrapCdata(String source) {
		return "<![CDATA[" + source + "]]>";
	}

	public static String decode(String s) {
		try {
			s = URLDecoder.decode(s, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
		return s;
	}

	/**
	 * 补全发票号
	 */
	public static String getBillNo(String oldBillNO, int b) {

		String newBillBO = "";
		String str = "1";
		for (int i = 0; i < oldBillNO.length(); i++) {
			str += "0";
		}

		newBillBO = String.valueOf(Long.parseLong(str) + Long.parseLong(oldBillNO) + b).substring(1);

		return newBillBO;
	}

	public static String subErrString(String source) {
		return subErrString(source, 0, 1000);
	}

	public static String subErrString(String source, int beginIndex, int endIndex) {
		if (NullsUtil.isEmpty(source)) {
			return "";
		} else {
			if (beginIndex < 0) {
				beginIndex = 0;
			}
			if (endIndex > source.length()) {
				endIndex = source.length();
			}
			return source.substring(beginIndex, endIndex);
		}
	}
	
	/**
	 * 日期间隔天数
	 * @param date1 大的日期
	 * @param date2 小的日期
	 * @return 天数
	 */
	public static int daysBetween(Date date1,Date date2){
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(date1);
		c2.setTime(date2);
		c1.set(Calendar.HOUR_OF_DAY, 0);
		c1.set(Calendar.MINUTE, 0);
		c1.set(Calendar.SECOND, 0);
		c2.set(Calendar.HOUR_OF_DAY, 0);
		c2.set(Calendar.MINUTE, 0);
		c2.set(Calendar.SECOND, 0);
		long rNum = c1.getTimeInMillis()-c2.getTimeInMillis();
		return (int)(rNum/86400/1000);
	}
	
	
	public static int compare_date(String DATE1, String DATE2,String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
    try {
        Date dt1 = df.parse(DATE1);
        Date dt2 = df.parse(DATE2);
        if (dt1.getTime() > dt2.getTime()) {
            return 1;
        } else if (dt1.getTime() < dt2.getTime()) {
            return -1;
        } else {
            return 0;
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }
    return 0;
	}



	public static void main(String[] args) {
		String s = "2013-09-07";
		System.out.println(daysBetween(new Date(),Convert.toParseDate(s)));
	}
}
